//
//  HMPicSelectViewController.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/22.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

/*
import UIKit

private let reuseIdentifier = "Cell"

let selectCellMargin: CGFloat = 4
let colCount = 3
private let maxImageCount = 5

let itemW = (ScreenWidth - (CGFloat(colCount) + 1) * selectCellMargin) / CGFloat(colCount)

class HMPicSelectViewController: UICollectionViewController {

    
    lazy var images: [UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let imageCount = images.count
        //限制图片最大添加张数
        let count = imageCount + (imageCount == maxImageCount ? 0 : 1)
        
        return count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HMPicSelectCell
    
        cell.delegate = self

        if indexPath.item == images.count {
            //需要给额外添加cell进行赋值图片的操作
            cell.image = nil
        } else {
            //不是额外添加的cell
            cell.image = images[indexPath.item]
        }

        return cell
    }
}

extension HMPicSelectViewController: HMPicSelectCellDelegate {
    
    func userWillAddPic() {
        let picker = UIImagePickerController()
        picker.delegate = self
        present(picker, animated: true, completion: nil)
    }
    
    func userWillRemovePic(cell: HMPicSelectCell) {
        let indexPath = collectionView?.indexPath(for: cell)
        images.remove(at: indexPath!.item)// 强制解包
        view.isHidden = images.count == 0
        collectionView?.reloadData()// 刷新
    }
}

extension HMPicSelectViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        images.append(image.scaleImage(width: ScreenWidth))
        
        // 刷新操作 加载完回到collectionView
        collectionView?.reloadData()
        
        dismiss(animated: true, completion: nil)
    }
}

@objc protocol HMPicSelectCellDelegate: NSObjectProtocol {
    //声明协议方法
    //用户将要添加图片
    @objc optional func userWillAddPic()
    //用户将要删除图片
    @objc optional func userWillRemovePic(cell: HMPicSelectCell)
}
// 自定义cell
class HMPicSelectCell: UICollectionViewCell {
    
    // 属性
    var image: UIImage? {
        didSet {
            addBtn.setImage(image, for: .normal)
            removeBtn.isHidden = image == nil
            let backImage: UIImage? = (image == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
            addBtn.setBackgroundImage(backImage, for: .normal)
        }
    }
    
    // 代理属性
    weak var delegate: HMPicSelectCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //添加删除和添加按钮
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        removeBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
    }
    
    @objc private func addBtnDidClick() {
        //addClosure?()
        //通过代理对象调用协议方法
        //如果当前cell的image 不为nil 就表示已经有图片
        if image != nil {
            print("人家已经有图片啦")
            return
        }
        delegate?.userWillAddPic?()
    }
    
    @objc private func removeBtnDidClick() {
        //removeClosure?()
        delegate?.userWillRemovePic?(cell: self)
    }
    
    private lazy var  addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    
    private lazy var removeBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        
        return btn
    }()
 
    
}

*/

import UIKit
import SVProgressHUD
private let reuseIdentifier = "Cell"

let selectCellMargin: CGFloat = 4
let colCount = 3
private let maxImageCount = 5

let itemW = (ScreenWidth - (CGFloat(colCount) + 1) * selectCellMargin) / CGFloat(colCount)


class HMPicSelectViewController: UICollectionViewController {
    
    lazy var images: [UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.register(HMPicSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    // MARK: UICollectionViewDataSource
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let imageCount = images.count
        //限制图片最大添加张数
        let count = imageCount + (imageCount == maxImageCount ? 0 : 1)
        return count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HMPicSelectCell
        cell.backgroundColor = randomColor()
        //指定代理对象
        cell.delegate = self
        //获取图片对象
        if indexPath.item == images.count {
            //需要给额外添加cell进行赋值图片的操作
            cell.image = nil
        } else {
            //不是额外添加的cell
            cell.image = images[indexPath.item]
        }
        
        return cell
    }
}

extension HMPicSelectViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //实现协议方法 没有实现协议方法之前 控制器可以自动dismiss
    //一旦实现了协议方法之后 控制器的dismiss 就交给了程序员
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        //获取图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //获取图片之后需要显示到collectionView中
        //将图片添加到数组中
        images.append(image.scaleImage(width: ScreenWidth))
        //刷新collectionView
        
        dismiss(animated: true, completion: nil)
        self.collectionView?.reloadData()
    }
}

//在分类中遵守协议 实现代理方法
extension HMPicSelectViewController: HMPicSelectCellDelegate {
    func userWillAddPic() {
        //调用图片选择器 添加图片
        
        /*
         保存的图片 + iCloud同步 + 相册
         //询问当前应用是否有访问相册的权限 如果没有就提示用户开启权限
         权限是第一次访问相册的时候用于授权的
         */
        //        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
        //            SVProgressHUD.showInfo(withStatus: "请您到设置->新浪微博->开启当前应用访问相册的权限")
        //            return
        //        }
        let picker = UIImagePickerController()
        //指定代理
        picker.delegate = self
        //是否允许编辑图片 在上传用户头像的时候需要开启
        //picker.allowsEditing = true
        present(picker, animated: true, completion: nil)
    }
    
    func userWillRemovePic(cell: HMPicSelectCell) {
        //1. 在数组中删除 '对应' 的元素
        //需要获取 indexPath   -> 需要获取被点击的cell
        let indexPath = collectionView?.indexPath(for: cell)
        self.images.remove(at: indexPath!.item)
        self.view.isHidden = self.images.count == 0
        //2. 刷新数据
        self.collectionView?.reloadData()
    }
}




@objc protocol HMPicSelectCellDelegate: NSObjectProtocol {
    //声明协议方法
    //用户将要添加图片
    @objc optional func userWillAddPic()
    //用户将要删除图片
    @objc optional func userWillRemovePic(cell: HMPicSelectCell)
}


//自定义cell
class HMPicSelectCell: UICollectionViewCell {
    
    var addClosure: (()->())?
    var removeClosure: (()->())?
    
    var image: UIImage? {
        didSet {
            //设置btn的图片
            addBtn.setImage(image, for: .normal)
            //设置删除按钮的隐藏和显示
            removeBtn.isHidden = image == nil
            let backImage: UIImage? = (image == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
            addBtn.setBackgroundImage(backImage, for: .normal)
        }
    }
    //声明弱引用的代理对象
    weak var delegate: HMPicSelectCellDelegate?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //添加删除和添加按钮
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        removeBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
    }
    
    @objc private func addBtnDidClick() {
        //addClosure?()
        //通过代理对象调用协议方法
        //如果当前cell的image 不为nil 就表示已经有图片
        if image != nil {
            print("人家已经有图片啦")
            return
        }
        delegate?.userWillAddPic?()
    }
    
    @objc private func removeBtnDidClick() {
        //removeClosure?()
        delegate?.userWillRemovePic?(cell: self)
    }
    
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        //设置视图显示模式
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    
    private lazy var removeBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        
        return btn
    }()
}

